package com.wstuo.common.config.userCustom.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.wstuo.common.config.userCustom.dao.IUserCustomDAO;
import com.wstuo.common.config.userCustom.dao.IViewDAO;
import com.wstuo.common.config.userCustom.dto.UserCustomDTO;
import com.wstuo.common.config.userCustom.dto.UserCustomQueryDTO;
import com.wstuo.common.config.userCustom.dto.ViewDTO;
import com.wstuo.common.config.userCustom.dto.ViewQueryDTO;
import com.wstuo.common.config.userCustom.entity.UserCustom;
import com.wstuo.common.config.userCustom.entity.View;
import com.wstuo.common.dto.PageDTO;
import com.wstuo.common.file.csv.CSVReader;
import com.wstuo.common.security.dao.IUserDAO;
import com.wstuo.common.security.entity.Role;
import com.wstuo.common.security.entity.User;
import com.wstuo.common.security.utils.AppContext;
import com.wstuo.common.security.utils.FileEncodeUtils;
import com.wstuo.common.util.StringUtils;


/**
 *  viewService
 * @author Mark
 *
 */
public class ViewService implements IViewService{
	private static final Logger LOGGER = Logger.getLogger(ViewService.class ); 
	private List<String> endUserDefaultView = null;
	private List<String> roleCodes = null;
	@Autowired
	private IViewDAO viewDAO;
	@Autowired
	private IUserCustomDAO userCustomDAO;
	@Autowired
	private IRowsWidthService rowsWidthService;
	@Autowired
	private IUserDAO userDAO;
	@Autowired
	private AppContext appctx;
	/**
	 *  分页查找视图
	 * @param dto
	 * @return PageDTO
	 */
	@Transactional
	@SuppressWarnings("unchecked")
	public PageDTO findPageView(ViewQueryDTO dto){
		PageDTO page = viewDAO.findPageView(dto);
		List<View> views = (List<View>) page.getData();
		List<ViewDTO> viewDTOs = new ArrayList<ViewDTO>(views.size());
		for(View view:views){
			ViewDTO viewdto = new ViewDTO();
			ViewDTO.entity2dto(view, viewdto);
			viewDTOs.add(viewdto);
		}
		page.setData(viewDTOs);
		return page;
	}
	
	/**
	 *  查询所有系统默认视图
	 * @return List<ViewDTO>
	 */
	@Transactional
	public List<ViewDTO> findAllSystemView(){
		if( endUserDefaultView == null || roleCodes == null ){
			initArray();
		}
		//是否需要限制视图查看
		boolean isPurview = false;
		User user = userDAO.findUniqueBy("loginName", appctx.getCurrentLoginName());
		if(user!=null && user.getRoles()!=null && user.getRoles().size()>0 ){
			Set<Role> rs = user.getRoles();
			for (Role r : rs) {
				if( roleCodes != null && roleCodes.contains(r.getRoleCode())){
					isPurview = true;
					break;
				}
			}
		}
		List<View> views = viewDAO.findBy("viewType","staticView");
		List<ViewDTO> viewDTOs = new ArrayList<ViewDTO>(views.size());
		String code = null;
		for(View view:views){
			boolean isDisplay = false;
			//如果有限制，并且视图的viewCode在endUserDefaultView存在（允许查看）；那么可以显示
			if( isPurview ){
				 if ( (code =  view.getViewCode()) != null 
							&& endUserDefaultView != null && endUserDefaultView.contains(code) ){
					isDisplay = true;
				 }
			}else{isDisplay = true;}
			if( isDisplay ){
				ViewDTO viewdto = new ViewDTO();
				ViewDTO.entity2dto(view, viewdto);
				viewDTOs.add(viewdto);
			}
		}
		return viewDTOs;
	}
	
	/**
	 *  查找所有视图
	 * @return List<ViewDTO>
	 */
	@Transactional
	public List<ViewDTO> findAllView(ViewQueryDTO dto){
		List<View> views = viewDAO.findListView(dto);
		List<ViewDTO> viewDTOs = new ArrayList<ViewDTO>(views.size());
		for(View view:views){
			ViewDTO viewdto = new ViewDTO();
			ViewDTO.entity2dto(view, viewdto);
			viewDTOs.add(viewdto);
		}
		return viewDTOs;
	}
	/**
	 * 排序ID
	 * @param idString
	 * @return List<String>
	 */
	private List<String> sortableDashboard(String idString){
		List<String> ids = new ArrayList<String>();
		if(StringUtils.hasText(idString)){
			String[] arrColumn = idString.split(":");
			for(String id:arrColumn){
				ids.add(id);
			}
		}
		return ids;
	}
	
	/**
	 *  检查该用户是否已经存在视图
	 * @param dto
	 * @return Long
	 */
	public boolean checkOutViewIsshow(ViewQueryDTO dto){
		//如果已经存在返回true
		boolean result = false;
		UserCustomDTO userCustomDTO = new UserCustomDTO();
		userCustomDTO.setUserCustomId(dto.getViewId());
		
		UserCustomQueryDTO userCustomQueryDTO = new UserCustomQueryDTO();
		userCustomQueryDTO.setLoginName(dto.getUserName());
		userCustomQueryDTO.setCustomType(dto.getCustomType());
		userCustomQueryDTO.setLimit(10);
		PageDTO pagedto = userCustomDAO.findPagerUserCustom(userCustomQueryDTO);
		//如果userCustom中已经有数据
		if(pagedto.getTotalSize()>0){
			//view里面有数据的话就不用添加.直接查看数据是不是自己拥有的,如果是拥有的什么都不用做直接返回null,如果还没有拥有的话,返回这个id回去就行了
			UserCustom userCustom = (UserCustom) pagedto.getData().get(0);
			UserCustomDTO.entity2dto(userCustom, userCustomDTO);
			//如果里面已经有字符串了
			if(userCustom.getViewIdStr() !=null && userCustom.getViewIdStr().length()>0){
				List<String> viewCodes = sortableDashboard(userCustom.getViewIdStr());
				for(String viewCode:viewCodes){
					if(viewCode.equals(dto.getViewCode())){
						result = true;break;
					}
				}
				
			}
		}
		return result;
	}
	
	/**
	 *  查找所有视图
	 *  @param dto
	 * @return UserCustomDTO
	 */
	@Transactional
	public UserCustomDTO findAllViewAndUserView(ViewQueryDTO dto){
		UserCustomDTO userCustomDTO = new UserCustomDTO();
		UserCustomQueryDTO userCustomQueryDTO = new UserCustomQueryDTO();
		userCustomQueryDTO.setLoginName(dto.getUserName());
		userCustomQueryDTO.setCustomType(dto.getCustomType());
		//查询该用户的自定义视图布局
		userCustomQueryDTO.setLimit(10);
		PageDTO pagedto = userCustomDAO.findPagerUserCustom(userCustomQueryDTO);
		List<ViewDTO> viewDTOs = null;
		
		if(pagedto.getTotalSize()>0 && pagedto.getData().size()>0){
			UserCustom userCustom = (UserCustom) pagedto.getData().get(0);
			UserCustomDTO.entity2dto(userCustom, userCustomDTO);
		}else{
			saveDefaultView(userCustomDTO);
		}
		if(userCustomDTO.getViewIdStr() !=null && userCustomDTO.getViewIdStr().length()>0){
			List<String> ids = sortableDashboard(userCustomDTO.getViewIdStr());
			List<String> viewRows = sortableDashboard(userCustomDTO.getViewRowsStr());
			viewDTOs = new ArrayList<ViewDTO>(ids.size());
			int i = 0;
			for(String id:ids){
				View view  = viewDAO.findUniqueBy("viewCode", id);
				if(view!=null){
					ViewDTO viewDTO = new ViewDTO();
					ViewDTO.entity2dto(view, viewDTO);
					viewDTO.setViewRow(viewRows.get(i));
					viewDTOs.add(viewDTO);
				}
				i++;
			}
		}
		userCustomDTO.setViewdtos(viewDTOs);
		userCustomDTO.setRowsWidth(rowsWidthService.findRowsWidthByLoginName(dto.getUserName()));
		
		return userCustomDTO;
	}
	/**
	 * 设置默认视图
	 */
	private void saveDefaultView(UserCustomDTO userCustomDTO){
		userCustomDTO.setLayoutType("twoRow");
		User user = userDAO.findUniqueBy("loginName", appctx.getCurrentLoginName());
		if(user!=null && user.getRoles()!=null && user.getRoles().size()>0 ){
			Set<Role> rs = user.getRoles();
			boolean bool=true;
			//Long filterId = filterService.getFilterViewId();
			for (Role r : rs) {
				String rc = r.getRoleCode();
				if(rc.equals("ROLE_ENDUSER") 
						|| rc.equals("ROLE_ITSOP_MANAGEMENT")){
					userCustomDTO.setViewRowsStr("1:1:2:");
					userCustomDTO.setViewIdStr("HotKnowledge:NewKnowledge:InstantMessage:");
					bool=false;
					break;
				}
			}
			if(bool){
				userCustomDTO.setViewRowsStr("1:1:1:1:1:2:2:2:2:2:");
				userCustomDTO.setViewIdStr("AssignToMeRequest:MyprocessingTasks:TasksAssignedtoOurTeam:InstantMessage:BulletinBoard:HotKnowledge:TaskRequestStatistics:");
			}
		}
	}
	/**
	 * 保存视图
	 * @param dto
	 */
	@Transactional
	public void saveView(ViewDTO dto){
		View viewEntity = viewDAO.findUniqueBy("viewCode", dto.getViewCode());
		if(viewEntity==null && dto.getViewType()!="staticView"){
			View view =new View();
			ViewDTO.dto2entity(dto, view);
			viewDAO.merge(view);
		}
	}

	/**
	 *  编辑视图
	 * @param dto
	 */
	@Transactional
	public void updateView(final ViewDTO dto){
		View view = viewDAO.findById(dto.getViewId());
		ViewDTO.dto2entity(dto, view);
		viewDAO.merge(view);
	}
	
	/**
	 *  根据ID删除视图
	 * @param ids
	 * @return boolean
	 */
	@Transactional
	public boolean deleteView(final Long[] ids){
		boolean b = true;
		for(Long id:ids){
			View view = viewDAO.findById(id);
			if(view.getDataFlag()==1){
				b = false;
				break;
			}
		}
		if(b){
			viewDAO.deleteByIds(ids);
		}
		return b;
	}
	/**
	 *  导入视图
	 * @param importFile
	 * @return String 
	 */
	@Transactional
	public String importViewData(File importFile){
		String result = "";
		int insert=0;
    	int update=0;
    	int total=0;
    	int failure=0;
    	try {
			String fileEncode = FileEncodeUtils.getFileEncode(importFile);
			Reader rd = new InputStreamReader(new FileInputStream(importFile), fileEncode);// 以字节流方式读取数据
			CSVReader reader=new CSVReader(rd);
			String [] line=null;
			try {
				while((line=reader.readNext())!=null){
					View view = new View();
					view.setViewName(line[0]);
					view.setViewType(line[1]);
					view.setViewContent(line[2]);
					view.setDataFlag(Byte.parseByte(line[3]));
					view.setViewCode(line[4]);
					viewDAO.save(view);
					insert++;
				 	total++;
				}
				result = "Total:"+total+",&nbsp;Insert:"+insert+",&nbsp;Update:"+update+",&nbsp;Failure:"+failure;
			} catch (Exception e) {
				LOGGER.error("import ViewData", e);
				result = "IOError";
			}
    	}catch (Exception e1) {
    		LOGGER.error("import ViewData", e1);
    		result = "FileNotFound";
		}
    	return result;
	}
	
	/**
	 *  导入系统默认数据
	 * @param importFile 导入文件
	 * @param defaultFilterId 默认的过滤器视图ID
	 * @param defaultReportId 默认的自定义视图ID
	 * @return String 导入结果
	 */
	@Transactional
	public String importSystemDefautlViewData(File importFile,Long defaultFilterId,Long defaultReportId){
		String result = "";
		int insert=0;
    	int update=0;
    	int total=0;
    	int failure=0;
    	try {
			String fileEncode = FileEncodeUtils.getFileEncode(importFile);
			Reader rd = new InputStreamReader(new FileInputStream(importFile), fileEncode);// 以字节流方式读取数据
			CSVReader reader=new CSVReader(rd);
			String [] line=null;
			try {
				while((line=reader.readNext())!=null){
					View view = new View();
					view.setViewName(line[0]);
					view.setViewType(line[1]);
					if("FCRProcessing".equals(line[4])){
						view.setViewContent(defaultFilterId.toString());
					}else if("CategoryStatictics".equals(line[4])){
						view.setViewContent(defaultReportId.toString());
					}else{
						view.setViewContent(line[2]);
					}
					view.setDataFlag(Byte.parseByte(line[3]));
					if("FCRProcessing".equals(line[4])){
						view.setViewCode("filterView_"+defaultFilterId);
					}else if("CategoryStatictics".equals(line[4])){
						view.setViewCode("singleView_"+defaultReportId);
					}else{
						view.setViewCode(line[4]);
					}
					viewDAO.save(view);
					insert++;
				 	total++;
				}
				result = "Total:"+total+",&nbsp;Insert:"+insert+",&nbsp;Update:"+update+",&nbsp;Failure:"+failure;
			} catch (Exception e) {
				LOGGER.error("import ViewData", e);
				result = "IOError";
			}
    	}catch (Exception e1) {
    		LOGGER.error("import ViewData", e1);
    		result = "FileNotFound";
		}
    	return result;
	}
	
	
	
	/**
	 * 修改视图默认显示行数
	 * @param viewDTO
	 * @return boolean
	 */
	@Transactional
	public boolean updateViewProportionById(ViewDTO viewDTO) {
		View view= viewDAO.findById(viewDTO.getViewId());
		view.setProportion(viewDTO.getProportion());
		viewDAO.merge(view);
		return true;
	}
	@Transactional
	public void upateViewCode() {
		// 获取所有userCustom
		List<UserCustom> list=userCustomDAO.findUserCustom(null);
		for (UserCustom userCustom : list) {
			if(userCustom!=null && StringUtils.hasText(userCustom.getViewIdStr())){
				String[] viewIds=userCustom.getViewIdStr().split(":");
				StringBuffer viewstr=new StringBuffer();
				for (int i = 0; i < viewIds.length; i++) {
					if(viewIds[i]!=""){
						View view= viewDAO.findById(Long.parseLong(viewIds[i]));
						if(view!=null){
							if(!"staticView".equals(view.getViewType())){
								view.setViewCode(view.getViewType()+"_"+view.getViewContent());
							}
							viewstr.append(view.getViewCode()+":");
						}
					}
				}
				userCustom.setViewIdStr(viewstr.toString());
				userCustomDAO.update(userCustom);
			}
		}
		
	}
	/**
	 * 初始化视图参数
	 */
	private void initArray(){
		//以下角色
		if( roleCodes == null ){
			roleCodes = new ArrayList<String>();
			roleCodes.add("ROLE_ENDUSER");
			roleCodes.add("ROLE_ITSOP_MANAGEMENT");
		}
		//允许看到的视图
		if( endUserDefaultView == null ){
			endUserDefaultView = new ArrayList<String>();
			endUserDefaultView.add("NewKnowledge");
			endUserDefaultView.add("HotKnowledge");
			endUserDefaultView.add("InstantMessage");
			endUserDefaultView.add("QuickCall");
		}
	}
	
	public List<String> getRoleCodes() {
		return roleCodes;
	}

	public List<String> getEndUserDefaultView() {
		return endUserDefaultView;
	}
}
